package com.icloud.system.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.icloud.common.cache.constants.CacheConstants;
import com.icloud.common.cache.service.RedisService;
import com.icloud.common.database.enums.AccessModeEnum;
import com.icloud.common.database.mapper.AppCustomerMapper;
import com.icloud.common.database.mapper.AttentionMapper;
import com.icloud.common.database.model.AppCustomer;
import com.icloud.common.database.model.Attention;
import com.icloud.common.web.enums.StateEnum;
import com.icloud.common.web.util.AuthUtil;
import com.icloud.system.boot.dto.HomeBrowsedPageDto;
import com.icloud.system.boot.mapper.HomeBrowsedMapper;
import com.icloud.system.boot.model.HomeBrowsed;
import com.icloud.system.boot.service.HomeBrowsedService;
import com.icloud.system.boot.vo.HomeBrowsedPageVo;
import com.icloud.system.boot.vo.HomeBrowsedVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 */
@Slf4j
@Service
public class HomeBrowsedServiceImpl extends ServiceImpl<HomeBrowsedMapper, HomeBrowsed> implements HomeBrowsedService {
    @Autowired
    private AppCustomerMapper appCustomerMapper;
    @Autowired
    private AttentionMapper attentionMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private AuthUtil authUtil;

    @Override
    public HomeBrowsedPageVo homeBrowsedPage(HomeBrowsedPageDto dto) {
        Long customerId = dto.getCustomerId();
        Long loginId = authUtil.getUserId();
        String accessMode = dto.getAccessMode();
        HomeBrowsedPageVo pageVo = new HomeBrowsedPageVo();

        LambdaQueryWrapper<HomeBrowsed> hbQuery = new LambdaQueryWrapper<>();
        hbQuery.eq(AccessModeEnum.isAccessed(accessMode), HomeBrowsed::getCustomerId, customerId);
        hbQuery.eq(AccessModeEnum.isVisited(accessMode), HomeBrowsed::getBrowserId, customerId);
        IPage<HomeBrowsed> hbPage = baseMapper.selectPage(Page.of(dto.getCurrent(), dto.getPageSize()), hbQuery);
        List<HomeBrowsed> hbList = hbPage.getRecords();
        if(CollectionUtils.isEmpty(hbList)){
            return pageVo;
        }
        pageVo.setTotal(hbPage.getTotal());

        List<Long> custIdList = null;
        // 访问我的
        if(AccessModeEnum.isAccessed(accessMode)) {
            custIdList = hbList.stream().map(HomeBrowsed::getBrowserId).collect(Collectors.toList());
        }
        // 我访问的
        if(AccessModeEnum.isVisited(accessMode)) {
            custIdList = hbList.stream().map(HomeBrowsed::getCustomerId).collect(Collectors.toList());
        }
        if(CollectionUtils.isEmpty(custIdList)){
            return pageVo;
        }
        LambdaQueryWrapper<AppCustomer> custQuery = new LambdaQueryWrapper<>();
        custQuery.in(AppCustomer::getId, custIdList);
        custQuery.eq(AppCustomer::getState, StateEnum.NORMAL.getCode());
        List<AppCustomer> customerList = appCustomerMapper.selectList(custQuery);
        Map<Long, AppCustomer> customerMap = customerList.stream().collect(Collectors.toMap(AppCustomer::getId, Function.identity()));

        // 我关注的
        LambdaQueryWrapper<Attention> attQuery = new LambdaQueryWrapper<>();
        attQuery.in(Attention::getFollowedId, custIdList);
        attQuery.eq(Attention::getCreatedId, customerId);
        List<Attention> attList = attentionMapper.selectList(attQuery);
        List<Long> attIdList = attList.stream().map(Attention::getFollowedId).collect(Collectors.toList());

        // 我的粉丝
        LambdaQueryWrapper<Attention> fansQuery = new LambdaQueryWrapper<>();
        fansQuery.eq(Attention::getFollowedId, customerId);
        fansQuery.in(Attention::getCreatedId, custIdList);
        List<Attention> fansList = attentionMapper.selectList(fansQuery);
        List<Long> fansIdList = fansList.stream().map(Attention::getCreatedId).collect(Collectors.toList());

        List<HomeBrowsedVo> hbVoList = new ArrayList<>();
        for(Long cId: custIdList) {
            AppCustomer appCustomer = customerMap.get(cId);

            HomeBrowsedVo hbVo = new HomeBrowsedVo();
            hbVo.setCustomerId(cId);
            if(appCustomer!=null) {
                String key = CacheConstants.CACHE_ACTIVE_USER + cId;
                Object cachedActiveTimeObj = redisService.get(key);
                Long cachedActiveTime = 0L;
                if (cachedActiveTimeObj instanceof Integer) {
                    cachedActiveTime = ((Integer) cachedActiveTimeObj).longValue();
                }
                if (cachedActiveTimeObj instanceof Long) {
                    cachedActiveTime = (Long) cachedActiveTimeObj;
                }
                hbVo.setLastAccessTime(cachedActiveTime);
                hbVo.setNickname(appCustomer.getNickname());
                hbVo.setAvatarUrl(appCustomer.getAvatarUrl());
            }
            // 我关注的
            if(attIdList.contains(cId)){
                hbVo.setAttention(true);
            }
            // 我的粉丝
            if(fansIdList.contains(cId)){
                hbVo.setFollowed(true);
            }
            // 互关
            if(hbVo.isAttention()&&hbVo.isFollowed()){
                hbVo.setEach(true);
            }
            hbVoList.add(hbVo);
        }
        pageVo.setHomeBrowsedVoList(hbVoList);
        return pageVo;
    }
}
